/*
 * Copyright (c) 2020. bmy
 */

import { ConfigureConfig } from "@config/configure.config";
import { GlobalMethod } from "@ann/register.annotation";

export class IndexUtils {

  /**
   * 动态返回接口基地址
   * @constructor
   */
  public static CheckAjaxUrl(): string {
    if(process.env.NODE_ENV === 'production') {
      return ConfigureConfig.AjaxConfig.ProdUrl;
    } else {
      return ConfigureConfig.AjaxConfig.DevUrl;
    }
  }

  /**
   * 方法上打上 @GlobalMethod() 注解，这个方法会自动成为vue的全局方法
   * 组件中直接：this.$setToken() 即可
   */
  @GlobalMethod
  public setToken(args: string): void {
    localStorage.setItem("token", args)
  }

  @GlobalMethod
  public setStorage<T extends [] | {} | string>(key: string, data: T): void {
    if (data.constructor == Array || data.constructor == Object) {
      localStorage.setItem(`moehu_${key}`, JSON.stringify(data));
    } else {
      // @ts-ignore
      localStorage.setItem(`moehu_${key}`, data.toString());
    }
  }

  @GlobalMethod
  public getStorage(key: String): typeof JSON | boolean | string{
    let Storage: string | null = localStorage.getItem(`moehu_${key}`);
    if (Storage == null) {
      return false
    } else {
      try {
        return JSON.parse(Storage);
      } catch (e) {
        return Storage;
      }
    }
  }


  @GlobalMethod
  public isPhone(phone: string): boolean {
    return /^1[3-9]\d{9}$/.test(phone)
  }
}
